package com.vertx.db;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.SqlConnection;

import java.util.function.Consumer;

public class FutureMysqlVerticle extends AbstractVerticle {
	public static void main(String[] args) {

		Runner.runExample(FutureMysqlVerticle.class);

	}

	private MySQLPool pool = null;

	public void start(Promise<Void> startPromise) throws Exception {

		MySQLConnectOptions connectOptions = new MySQLConnectOptions()
				.setPort(3306)
				.setHost("localhost")
				.setDatabase("testdb")
				.setUser("root")
				.setPassword("water123");

		// Pool options
		PoolOptions poolOptions = new PoolOptions()
				.setMaxSize(5);

		// Create the client pool
		pool = MySQLPool.pool(this.vertx, connectOptions, poolOptions);

//		//第一步 获取数据库链接
//		pool.getConnection(con -> {
//			if(con.succeeded()){
//				SqlConnection sqlConnection = con.result();
//				//第二步 用获取的数据库链接查询数据库
//				sqlConnection.preparedQuery("select * from t_person")
//						.execute(rs -> {
//							sqlConnection.close();
//							//第三步 加工查询出来的数据 并返回给客户端
//							if (rs.succeeded()) {
//								rs.result().forEach(item -> {
//									System.out.println("id : " + item.getInteger(0) + ", first name: " +
//											item.getString(1) + ", second name: " + item.getString(2));
//								});
//							}else {
//								System.out.println("fail : " + rs.cause().getMessage());
//							}
//						});
//			}else{
//				System.out.println("fail : " + con.cause().getMessage());
//			}
//		});

		this.getCon().compose(con -> this.getRows(con)).onSuccess(rows -> consumer.accept(rows));
	}

	Consumer<RowSet<Row>> consumer = new Consumer<RowSet<Row>>() {
		@Override
		public void accept(RowSet<Row> rows) {
			rows.forEach(item -> {
				System.out.println("id : " + item.getInteger(0) + ", first name: " +
						item.getString(1) + ", second name: " + item.getString(2));
			});
		}
	};

	private Future<SqlConnection> getCon() {
		Promise<SqlConnection> promise = Promise.promise();
		pool.getConnection(con -> {
			if (con.succeeded()) {
				SqlConnection sqlConnection = con.result();
				promise.complete(sqlConnection);
			} else {
				System.out.println("fail : " + con.cause().getMessage());
			}
		});
		return promise.future();
	}

	private Future<RowSet<Row>> getRows(SqlConnection sqlConnection) {
		Promise<RowSet<Row>> promise = Promise.promise();
		sqlConnection.preparedQuery("select * from t_person limit 10")
				.execute(rs -> {
					sqlConnection.close();
					//第三步 加工查询出来的数据 并返回给客户端
					if (rs.succeeded()) {
						promise.complete(rs.result());
					} else {
						System.out.println("fail : " + rs.cause().getMessage());
					}
				});
		return promise.future();
	}

}
